var clientPC = navigator.userAgent.toLowerCase();
var isIE  = ((clientPC.indexOf("msie") !== -1) && (clientPC.indexOf("opera") === -1));
var isWin = ((clientPC.indexOf("win") !== -1) || (clientPC.indexOf("16bit") !== -1));
var id;
var stored_selection = '';
var puw;                    // Popup window
function CreateBBTag(opener, closer, area) {
    if (isIE && isWin)
         CreateBBTag_IE(opener, closer, area);
    else CreateBBTag_nav(opener, closer, area);
    return;
}
function CreateBBTag_nav(opener, closer, area) {
    id = document.getElementById(area);
    if (id.selectionEnd && (id.selectionEnd - id.selectionStart > 0)) {
        preString  = (id.value).substring(0, id.selectionStart);
        newString  = opener + (id.value).substring(id.selectionStart, id.selectionEnd) + closer;
        postString = (id.value).substring(id.selectionEnd);
        id.value   = preString + newString + postString;
        id.focus();
    } else {
        var offset = id.selectionStart;
        preString  = (id.value).substring(0, offset);
        newString  = opener + closer;
        postString = (id.value).substring(offset);
        id.value   = preString + newString + postString;
        id.selectionStart = offset + opener.length;
        id.selectionEnd   = offset + opener.length;
        id.focus();
    }
    return;
}
function CreateBBTag_IE(opener, closer, area) {
    id = document.getElementById(area);
    var aSelection = document.selection.createRange().text;
    var range = id.createTextRange();
    if (aSelection) {
        document.selection.createRange().text = opener + aSelection + closer;
        id.focus();
        range.move('textedit');
        range.select();
    } else {
        var oldStringLength = range.text.length + opener.length;
        id.value += opener + closer;
        id.focus();
        range.move('character', oldStringLength);
        range.collapse(false);
        range.select();
    }
    return;
}
function RemoveBBTag(area) {
    id = document.getElementById(area);
    var text = '';
    if (id.value !== undefined) {
        text = id.value;
        text = text.replace (/\[[^\]]*\]/g, '');
        id.value = text;
    } else if (id.innerText !== undefined) {
        text = id.innerText;
        text = text.replace (/\[[^\]]*\]/g, '');
        id.innerText = text;
    } else {
        text = id.textContent;
        text = text.replace (/\[[^\]]*\]/g, '');
        id.textContent = text;
    }
}
// Show hidden additionsl input field.
function OpenField(field, area) {
    id = document.getElementById(area);
    if (!id.selectionEnd || (id.selectionEnd - id.selectionStart === 0)) {
        document.getElementById(field + area).style.display = 'block';
    }
}
function GetFromDropDown(val, name, area) {
    if (!val) return;
    if (name === 'colors')   CreateBBTag('[color="' + val + '"]','[/color]', area);
    if (name === 'bgcolors') CreateBBTag('[bgcolor="' + val + '"]','[/bgcolor]', area);
    if (name === 'format')   CreateBBTag('[' + val + ']' + val,'[/' + val + ']', area);
    if (name === 'typeface') CreateBBTag('[font="' + val + '"]','[/font]', area);
    if (name === 'size')     CreateBBTag('[size=' + val + ']','[/size]', area);
}
function AddLink(type, area, link) {
    if (isIE && isWin)
         AddLink_IE(type, area, link);
    else AddLink_nav(type, area, link);
    return;
}
function AddLink_nav(type, area, link) {
    var text = bb = '';
    id = document.getElementById(area);
    if (id.selectionEnd && (id.selectionEnd - id.selectionStart > 0))
         text = (id.value).substring(id.selectionStart, id.selectionEnd);
    else text = document.getElementById('txt_' + area).value;
    var preString  = '';
    var postString = '';
    if (text) {
        preString = (id.value).substring(0, id.selectionStart);
        bb = '[' + type + '=' +link + ']' + text + '[/' + type + ']';
        postString = (id.value).substring(id.selectionEnd);
        id.value   = preString + bb + postString;
        id.focus();
        return;
    } else bb = '[' + type + ']' + link + '[/' + type + ']';
    var offset = id.selectionStart;
    preString  = (id.value).substring(0, offset);
    postString = (id.value).substring(offset);
    id.value   = preString + bb + postString;
    id.selectionStart = offset + opener.length;
    id.selectionEnd   = offset + opener.length;
    id.focus();
    return;
}
function AddLink_IE(type, area, link) {
    var text = '';
    id = document.getElementById(area);
    var aSelection = document.selection.createRange().text;
    var range = id.createTextRange();
    if (aSelection)
         text = aSelection;
    else text = document.getElementById('txt_' + area).value;
    if (text) {
        document.selection.createRange().text = '[' + type + '=' + link + ']' + text + '[/' + type + ']';
        id.focus();
        range.move('textedit');
        return;
    } else {
        id.value += '[' + type + ']' + link + '[/' + type + ']';
        id.focus();
        range.collapse(false);
        range.select();
        return;
    }
}
function AddList(type, area) {
    if (isIE && isWin)
         AddList_IE(type, area);
    else AddList_nav(type, area);
    return;
}
function AddList_nav(type, area) {
    id = document.getElementById(area);
    var offset = id.selectionStart;
    var minus  = 0;
    var opener = '[' + type + ']';
    var closer = '[/' + type + ']';
    minus += 1;
    var items = new Array();
    var itemString = '';
    var item  = '';
    while (item === prompt('Enter an item.\nLeave the box empty or click Cancel to complete the list', '')) {
        items.push('[*]' + item + '[/*]');
    }
    itemString = items.join('');
    itemsize   = items.length;
    minus += itemsize;
    var preString  = (id.value).substring(0, offset);
    var newString  = opener + itemString + closer;
    var postString = (id.value).substring(offset);
    id.value  = preString + newString + postString;
    id.selectionStart = offset + newString.length - minus;
    id.selectionEnd   = offset + newString.length - minus;
    id.focus();
    return;
}
function AddList_IE(type, area) {
    id = document.getElementById(area);
    var range  = id.createTextRange();
    var minus  = 0;
    var opener = '[' + type + ']';
    var closer = '[/' + type + ']';
    minus += 1;
    var items = new Array();
    var itemString = '';
    var item;
    while (item === prompt('Enter an item.\nLeave the box empty or click Cancel to complete the list', '')) {
        items.push('[*]' + item + '[/*]');
    }
    itemString = items.join('');
    itemsize   = items.length;
    minus += itemsize;
    tag = opener + itemString + closer;
    var oldStringLength = range.text.length + tag.length - minus;
    id.value += tag;
    id.focus();
    range.move('character', oldStringLength);
    range.collapse(false);
    range.select();
    return;
}
function SetSmile(tag, area) {
    id = document.getElementById(area);
    var offset = id.selectionStart;
    preString  = (id.value).substring(0, offset);
    postString = (id.value).substring(offset);
    id.value   = preString + tag + postString;
    id.focus();
    return;
}
function MozWrap(area, open, close) {
    var selLength = area.textLength;
    var selStart  = area.selectionStart;
    var selEnd    = area.selectionEnd;
    if (selEnd === 1 || selEnd === 2) selEnd = selLength;
    var s1 = (area.value).substring(0, selStart);
    var s2 = (area.value).substring(selStart, selEnd);
    var s3 = (area.value).substring(selEnd, selLength);
    area.value = s1 + open + s2 + close + s3;
    return;
}
function InsertText(area, text) {
    if (area.createTextRange && area.caretPos) {
        var caretPos = area.caretPos;
        caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) === ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
    } else {
        var selStart = area.selectionStart;
        var selEnd   = area.selectionEnd;
        MozWrap(area, text, '');
        area.selectionStart = selStart + text.length;
        area.selectionEnd   = selEnd + text.length;
    }
}
function CheckSelection() {
    var myselection = '';
    if (window.getSelection)        myselection = window.getSelection();
    else if (document.selection)    myselection = document.selection.createRange().text;
    else if (document.getSelection) myselection = document.getSelection();
    if ((myselection !== '') && (myselection !== null)) {
        if (myselection !== stored_selection ) {
            stored_selection = (myselection.toString() !== '') ? myselection.toString() : null;
        }
    } else stored_selection = null;
}
function AddQuote(area) {
    if ((stored_selection !== '') && (stored_selection !== null)) {
        InsertText(area, '[quote]' + stored_selection + '[/quote]\n');
    }
    return false;
}
// The possibility to open and close additional form with the same button
function ShowForm(area) {
    id = document.getElementById(area);
    if (id.style.display === 'none')
         id.style.display = 'block';
    else id.style.display = 'none';
}
function SetImagesPath(val) {
    category = val.options[val.selectedIndex].value;
}
function OpenBrowseWin(area, url) {
    id = area;
    puw = window.open(url, 'popWin', 'menubar=no,toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=640,height=480,top=100,status=no');
    puw.focus();
}
function InsertImage(area, url) {
    var dialog = 'image_' + area;
    id = document.getElementById(area);
    if (!url) url = document.getElementById('image_url_' + area).value;
    preString = (id.value).substring(0, id.selectionStart);
    bb = '[img]' + url + '[/img]';
    postString = (id.value).substring(id.selectionEnd);
    id.value   = preString + bb + postString;
    id.focus();
    HideDialog(dialog);
}
function ChooseColor(cmd, area) {
    document.getElementById('cmd_' + area).value = cmd;
    ShowForm('color_' + area);
}
function ViewColor(color, area) {
    id = document.getElementById('clr_val_' + area);
    if (!color) color = id.value;
    document.getElementById('preview_' + area).style.backgroundColor = color;
    id.value = color;
}
function SetColor(color, area) {
    var cmd = document.getElementById('cmd_' + area).value;
    if (!color) color = document.getElementById('clr_val_' + area).value;
    if (cmd === 'color') CreateBBTag('[color="' + color + '"]','[/color]', area);
    else if (cmd === 'bgcolor') CreateBBTag('[bgcolor="' + color + '"]','[/bgcolor]', area);
    HideDialog('color_' + area);
}
function AddUrl(cmd, area) {
    document.getElementById('type_' + area).value = cmd;
    // This field will be open while typing
    if (cmd === 'mp3') document.getElementById('label_' + area).style.display = 'none';
    ShowForm('link_' + area);
}
function InsertLink(area) {
    var url = document.getElementById('url_' + area).value;
    var cmd = document.getElementById('type_' + area).value;
    switch(cmd) {
        case "url":
            AddLink('url', area, url);
            break;
        case "mp3":
            AddLink('mp3', area, url);
            break;
        case "email":
            AddLink('email', area, url);
            break;
        default:
            break;
    }
    document.getElementById(area).focus();
    HideDialog('link_' + area);
}
function HideDialog(dialog) {
    document.getElementById(dialog).style.display = 'none';
}
function Preview(area, url) {
    var text = '';
    // Preview width must be equql with #layout-center
    var width = screen.width - 450;
    var id_txt = document.getElementById(area);
    // Fucking browsers standards...
    if (id_txt.value !== undefined)
         text = id_txt.value;
    else if (id_txt.innerText !== undefined)
         text = id_txt.innerText;
    else text = id_txt.textContent;
    // We can't parse lines endings in popup window
    text = text.replace (/(\r\n|\n)/gm, '<br />');
    // Now we create hidden form to send preview data in popup window
    var h_form = document.createElement('FORM');
    h_form.setAttribute('action', url);
    // Method POST is choosen for bbCodes parsing.
    h_form.setAttribute('method', 'POST');
    h_form.setAttribute('target', 'preview');
    h_form.style.display = 'none';
    // Article title. It is empty when user post comment or reply in forum
    var title = '';
    var id_title = document.getElementById('title');
    if (id_title != undefined) title = id_title.value;
    var element = document.createElement('INPUT');
    element.setAttribute('type', 'text');
    element.setAttribute('name', 'title');
    element.setAttribute('value', title);
    h_form.appendChild(element);
    element = document.createElement('INPUT');
    element.setAttribute('type', 'text');
    element.setAttribute('name', 'text');
    element.setAttribute('value', text);
    h_form.appendChild(element);
    document.body.appendChild(h_form);
    puw = window.open(url, 'preview', 'menubar=no,toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=' + width + ',height=500,top=50,status=no');
    puw.focus();
    h_form.submit();
    // We don't need this form any more.
    document.body.removeChild(h_form);
//    h_form.removeNode(true);
}
